Telegram Group & Telegram Channel
🔓Что выведет следующий код?


#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base constructor: ";
call();
}
virtual void call() { cout << "Base::call\n"; }
};

class Derived : public Base {
int x = init();

int init() {
cout << "Derived::init\n";
return 42;
}

public:
Derived() {
cout << "Derived constructor\n";
}

void call() override {
cout << "Derived::call, x = " << x << "\n";
}
};

int main() {
Derived d;
return 0;
}


🔢Варианты ответа:

A)

Derived::init
Derived constructor


B)

Derived::init
Derived constructor


C)

Base constructor: Derived::call, x = 42
Derived constructor


D)

Derived::call, x = <undefined>
Derived::init
Derived constructor


Правильный ответ: B

💡Почему?
В момент вызова конструктора Base, объект ещё не стал Derived. Виртуальная функция вызывается в контексте Base.



tg-me.com/cpluspluc/1034
Create:
Last Update:

🔓Что выведет следующий код?


#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base constructor: ";
call();
}
virtual void call() { cout << "Base::call\n"; }
};

class Derived : public Base {
int x = init();

int init() {
cout << "Derived::init\n";
return 42;
}

public:
Derived() {
cout << "Derived constructor\n";
}

void call() override {
cout << "Derived::call, x = " << x << "\n";
}
};

int main() {
Derived d;
return 0;
}


🔢Варианты ответа:

A)

Derived::init
Derived constructor


B)

Derived::init
Derived constructor


C)

Base constructor: Derived::call, x = 42
Derived constructor


D)

Derived::call, x = <undefined>
Derived::init
Derived constructor


Правильный ответ: B

💡Почему?
В момент вызова конструктора Base, объект ещё не стал Derived. Виртуальная функция вызывается в контексте Base.

BY C++ Academy


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpluspluc/1034

View MORE
Open in Telegram


C Academy Telegram | DID YOU KNOW?

Date: |

However, analysts are positive on the stock now. “We have seen a huge downside movement in the stock due to the central electricity regulatory commission’s (CERC) order that seems to be negative from 2014-15 onwards but we cannot take a linear negative view on the stock and further downside movement on the stock is unlikely. Currently stock is underpriced. Investors can bet on it for a longer horizon," said Vivek Gupta, director research at CapitalVia Global Research.

C Academy from us


Telegram C++ Academy
FROM USA